package com.example.springmvcdemo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController{
    @RequestMapping("/hello")
    public String sayHello() {
        return "hello";
    }
    @RequestMapping("/getC")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        //String name = request.getParameter("name");
        Cookie[] cookies = request.getCookies();
        if(cookies!=null) {
            Arrays.stream(cookies).forEach(ck-> System.out.println(ck.getName() +":" +ck.getValue()));
        }
        return "获取cookie";
    }

    @RequestMapping("/getC2")
    public String getCookie2(@CookieValue("bite") String bite) {
        return "从Cookie中获取值, bite:" + bite;
    }

    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return "设置setsess成功";
    }

    @RequestMapping("/getSess")
    public String getSess(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String name = (String)session.getAttribute("name");
        return "从Session中获取name: " + name;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "从header中获取信息, userAgent:" + userAgent;
    }


    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("user-Agent") String userAgent) {
        return "从header中获取信息, userAgent:" + userAgent;
    }
}
